import MSFile
import MSEvent

import os


class MSObject:
    def __init__(self):
        self.objectMSId     = 0
        self.objectMSKey    = ''
        self.objectPCNId    = 0

        self.objectId       = 0 #initialized from one of the fields externally but it is a primary obj key
        self.msLogin        = ""

    def __cmp__(self, y):
        if self.objectId < y.objectId: return -1
        if self.objectId > y.objectId: return 1
        return 0

    def __hash__(self):
        return self.objectId

def readObjectsFromFile(filename, objects):
    def parse(cfgline):
        s = cfgline.strip().split(' ')
        e = {}
        for prop in s[0:len(s)]:
            prop = prop.split('=')
            e[prop[0]] = prop[1]
        return e
    def insert(objects, y):
        found = False
        for o in objects:
            if o.objectId == y.objectId:
                o.objectMSId    = y.objectMSId
                o.objectPCNId   = y.objectPCNId
                o.objectMSKey   = y.objectMSKey
        if not found:
            objects.append(o)

    f = open(filename, 'r')
    sdata = f.readlines()
    for s in sdata:
        e = parse(s)
        o = MSObject()

        o.objectMSId    = int(e['obj_msid'])
        o.objectPCNId   = int(e['obj_pcnid'])
        o.objectMSKey   = e['obj_skey']
        o.objectId      = o.objectMSId
        insert(objects, o)

    return objects

def readObjectsFromMSDB(dbcursor, objects):
    def insert(objects, y):
        found = False
        for o in objects:
            if o.objectId == y.objectId:
                o.objectMSId    = y.objectMSId
                o.objectPCNId   = y.objectPCNId
                o.objectMSKey   = y.objectMSKey
        if not found:
            objects.append(o)

    query = 'SELECT id,uid FROM _devices'
    dbcursor.execute(query)
    uids = dbcursor.fetchall()
    for u in uids:
        try:
            query = 'SELECT login,password FROM _users WHERE defaultDevice=%s' % (str(uid[0]))
            dbcursor.execute(query)
            ddata = dbcursor.fetchall()
            o = MSObject()
            o.objectMSId    = int(uid[0])
            o.objectPCNId   = int(ddata[0][0].replace('dev',''))
            o.objectId = o.objectMSId
            insert(objects, o)
        except: continue
    return objects

def initObjects(objlist, objdict, storageroot):
    for o in objlist:
        if not objdict.has(o):
            objdict[o] = MSFile.MSFile(storageroot, 'obj.' + str(o.objectId))
            objdict[o].load()

def saveObjects(objdict):
    for o, d in objlist.iteritems(): d.save()






if __name__ == "__main__":
    import sys
    if len(sys.argv) != 2: print "Usage: %s <storage_root>" % (sys.argv[0])
    g_root = sys.argv[1]
    
    def case1():
        o = MSObject()
        o.objectMSId    = 1
        o.objectPCNId   = 2
        o.objectMSKey   = 'xep'
        o.objectId = o.objectMSId
        o.open(g_root)
        o.close()

    case1()
